package com.mercadopago;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;

import com.mercadopago.types.Operation;
import com.mercadopago.types.PaymentMethod;
import com.mercadopago.types.Status;

public class ProcessAutomaticResponse {

	private Operation operation;
	
	private HttpServletRequest request;
	
	private ProcessAutomaticResponse() {}
	
	public static Operation process(HttpServletRequest request) {
		ProcessAutomaticResponse processAutomaticResponse = new ProcessAutomaticResponse();
		processAutomaticResponse.setRequest(request);
		processAutomaticResponse.extractData();
		return processAutomaticResponse.getOperation();
	}
	
	private Status convertToEnumStatus(String param) {
		String value = request.getParameter(param);
		for(Status status : Status.values()) {
			if(status.value().equals(value))
				return status;
		}
		return null;
	}
	
	private PaymentMethod convertToEnumPaymentMethod(String param) {
		String value = request.getParameter(param);
		for(PaymentMethod paymentMethod : PaymentMethod.values()) {
			if(paymentMethod.value().equals(value))
				return paymentMethod;
		}
		return null;
	}
	
	private Long convertToLong(String param) {
		return Long.parseLong(request.getParameter(param));
	}
	
	private BigDecimal convertToBigDecimal(String param) {
		return new BigDecimal(convertToLong(param));
	}
	
	private void extractData() {
		operation = new Operation();
		operation.setSeller_op_id(request.getParameter("seller_op_id"));
		operation.setMp_op_id(convertToLong("mp_op_id"));
		operation.setAcc_id(convertToLong("acc_id"));
		operation.setStatus(convertToEnumStatus("status"));
		operation.setItem_id(request.getParameter("item_id"));
		operation.setName(request.getParameter("name"));
		operation.setPrice(convertToBigDecimal("price"));
		operation.setShipping_amount(convertToBigDecimal("shipping_amount"));
		operation.setAdditional_amount(convertToLong("additional_amount"));
		operation.setTotal_amount(convertToBigDecimal("total_amount"));
		operation.setExtra_part(request.getParameter("extra_part"));
		operation.setPayment_method(convertToEnumPaymentMethod("payment_method"));
	}

	public Operation getOperation() {
		return operation;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
}
